package com.itao.dom4j;

import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @Author sjt
 * @CreateTime 2023/10/15 14:10
 */
public class Dom4jTest {

    public static void main(String[] args)  throws Exception {
        //read();
        write();
    }

    private static void read() throws Exception {
        var saxReader = new SAXReader();
        var document = saxReader.read("E:\\idea\\java-learn\\xml\\src\\main\\resources\\read.xml");
        // 获取根元素
        var rootElement = document.getRootElement();
        System.out.println("rootElement:" + rootElement.getName());
        // 获取子节点（不包括孙子节点）
        var subElements = rootElement.elementIterator();
        while (subElements.hasNext()) {
            var element = subElements.next();
            // 获取标签名
            System.out.println(element.getName());
            // 获取属性
            System.out.println(element.attribute("no").getValue());
        }
    }

    private static void write() throws Exception {
        var document = DocumentHelper.createDocument();

        var school = document.addElement("school");

        var aClass = school.addElement("class");
        aClass.addAttribute("no", "1801");

        var student = aClass.addElement("student");
        student.addAttribute("no", "1");
        var name = student.addElement("name");
        name.addText("张鹏飞");
        var sex = student.addElement("sex");
        sex.addText("男");
        var addr = student.addElement("addr");
        addr.addText("武汉");

        var format = OutputFormat.createPrettyPrint();
        format.setEncoding(StandardCharsets.UTF_8.name());
        try (var os = new FileOutputStream("E:\\idea\\java-learn\\xml\\src\\main\\resources\\dom4j-write.xml")){
            var xmlWriter = new XMLWriter(os, format);
            xmlWriter.write(document);
        }
    }
}
